// 文件名称：settings.js
// 完整保存路径：miniprogram/pages/notification/settings/settings.js
// 功能说明：通知设置页面逻辑控制
// 使用说明：处理通知设置的获取、更新等功能

const { getToken } = require('../../../utils/auth.js');

const app = getApp();

Page({
  data: {
    settings: [],
    loading: false,
    saving: false
  },

  onLoad() {
    console.log('通知设置页面加载');
    this.loadSettings();
  },

  /**
   * 加载通知设置
   */
  async loadSettings() {
    try {
      this.setData({ loading: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/notifications/settings`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (response.statusCode === 200 && response.data.success) {
        // 如果没有设置记录，使用默认设置
        let settings = response.data.data;
        if (!settings || settings.length === 0) {
          settings = this.getDefaultSettings();
        }
        
        this.setData({
          settings: settings,
          loading: false
        });
      } else {
        throw new Error(response.data.message || '获取通知设置失败');
      }
      
    } catch (error) {
      console.error('加载通知设置失败:', error);
      this.setData({ loading: false });
      
      // 如果获取失败，使用默认设置
      this.setData({
        settings: this.getDefaultSettings()
      });
      
      wx.showToast({
        title: '加载设置失败，使用默认设置',
        icon: 'none'
      });
    }
  },

  /**
   * 获取默认通知设置
   */
  getDefaultSettings() {
    return [
      {
        notification_type: 'system',
        type_name: '系统通知',
        description: '系统维护、更新等重要通知',
        enabled: true,
        wechat_enabled: true,
        app_enabled: true
      },
      {
        notification_type: 'intervention',
        type_name: '干预提醒',
        description: '干预计划、提醒等相关通知',
        enabled: true,
        wechat_enabled: true,
        app_enabled: true
      },
      {
        notification_type: 'vision',
        type_name: '视力检查',
        description: '视力检查提醒、结果通知等',
        enabled: true,
        wechat_enabled: false,
        app_enabled: true
      },
      {
        notification_type: 'share',
        type_name: '社交分享',
        description: '点赞、评论、关注等社交活动通知',
        enabled: false,
        wechat_enabled: false,
        app_enabled: true
      }
    ];
  },

  /**
   * 切换通知开关
   */
  onToggleEnabled(e) {
    const index = e.currentTarget.dataset.index;
    const field = e.currentTarget.dataset.field;
    const settings = this.data.settings;
    
    settings[index][field] = !settings[index][field];
    
    this.setData({ settings });
  },

  /**
   * 保存设置
   */
  async saveSettings() {
    if (this.data.saving) return;
    
    try {
      this.setData({ saving: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/notifications/settings`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            settings: this.data.settings
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (response.statusCode === 200 && response.data.success) {
        wx.showToast({
          title: '设置保存成功',
          icon: 'success'
        });
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        throw new Error(response.data.message || '保存设置失败');
      }
      
    } catch (error) {
      console.error('保存设置失败:', error);
      wx.showToast({
        title: error.message || '保存设置失败',
        icon: 'error'
      });
    } finally {
      this.setData({ saving: false });
    }
  },

  /**
   * 重置为默认设置
   */
  resetToDefault() {
    wx.showModal({
      title: '重置设置',
      content: '确定要重置为默认设置吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            settings: this.getDefaultSettings()
          });
          
          wx.showToast({
            title: '已重置为默认设置',
            icon: 'success'
          });
        }
      }
    });
  }
});
